function drawImage(ctx, image, container, canvasWidthInch, canvasHeightInch,scale) {
	var img = new Image();
	img.src = $(image).attr('src');

	var args = [];
	args[0] = $(image).offset().left;
	args[1] = $(image).width();
	args[2] = $(image).offset().top;
	args[3] = $(image).height();

	args[4] = $(container).offset().left;
	args[5] = $(container).width();
	args[6] = $(container).offset().top;
	args[7] = $(container).height();

	args[8] = img.width;
	args[9] = img.height;
	
	args[10] = canvasWidthInch;
	args[11] = canvasHeightInch;

	// alert(args);
	// alert(img.src);

	var result = calculateDrawData(args);

	sourceX = result[0];
	sourceY = result[1];
	;
	sourceWidth = result[2];
	sourceHeight = result[3];
	;
	destX = result[4];
	destY = result[5];
	destWidth = result[6];
	destHeight = result[7];
	
	dpiX = result[8];
	dpiY = result[9];
	
	validateDpiX(dpiX, dpiY, image);
	
	//alert(img + " ; " + sourceX + " ; " + sourceY + " ; " + sourceWidth + " ; " + sourceHeight + " ; " + destX + " ; " + destY + " ; " + destWidth + " ; " + destHeight);
	ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, destX/scale, destY/scale, destWidth/scale, destHeight/scale);
}

function dpiWarn(message){
	alert(message);
}

function validateDpiX(dpiX, dpiY, image){
	var imageId = $(image).attr("id");
	var dpi = $("#dpi").html();
	if((dpiX > 0 ) &&(dpiX < dpi)){
		dpiWarn("dpi van afbeelding met id (" + imageId + ") is te laag in horizontale richting");
	} else if((dpiY > 0 ) &&(dpiY < dpi)){
		dpiWarn("dpi van afbeelding met id (" + imageId + ") te laag in verticale richting");
	}
}

function readURL(input, imageId, previewImageClass, scale) {
	if (input.files && input.files[0]) {
		var reader = new FileReader();
		var scale = $("#scaleHolder").html();
		
		reader.onload = function(e) {
			var image_template_data = [ {
				image_id : imageId,
				image_url : e.target.result,
				image_width : e.width * 1 * scale,
				image_height : e.height * 1 * scale
			} ];
			$.when(
					addImage(image_template_data, imageId),
					$("#imageUploadDialog " + previewImageClass).html(
							'<img src="' + e.target.result + '" style="max-width: 100px; max-height: 100px;"/>')).then(init());
		};
		reader.readAsDataURL(input.files[0]);
	}
}
Query.fn.exists = function(){return this.length>0;}

function addImage(image_template_data, imageId){
	if($('#' + imageId).length == 0) {
		var id = imageId.replace("image", "");
		
		var newImageId = "image" + (--id);
		var placeFound = $("#workspace #" + newImageId).length > 0;
		while(id > 0 && !placeFound){
			newImageId = "image" + (--id);
			placeFound = $("#workspace #" + newImageId).length > 0;
		}
		if("image0" == newImageId){
			var scale = $("#scaleHolder").html();
			$.when(
				$("#workspace_image_template").tmpl(image_template_data).appendTo("#workspace")
			).then(
				scaleImage(imageId, scale)
			);
		} else {
			$.when(
				$("#workspace_image_template").tmpl(image_template_data).insertAfter($("#workspace #" + newImageId).parent())
			).then(
					scaleImage(imageId, scale)
			);
		}
	}
}

function scaleImage(imageId, scale){
	var factor = 0.1;
	var imageWidth = $("#workspace #" + imageId).width();
	var extendedCanvasWidth = $("#extendedCanvas").css("width").replace("px", "");
	if(extendedCanvasWidth < imageWidth){
		$("#workspace #" + imageId).width(extendedCanvasWidth * (1 + factor));
	}
	
	var imageHeight = $("#workspace #" + imageId).height();
	var extendedCanvasHeight = $("#extendedCanvas").css("height").replace("px", "");
	if(extendedCanvasHeight < imageHeight){
		$("#workspace #" + imageId).width(extendedCanvasHeight * (1 + factor));
	}
}

function init() {
	initDeleteImage();
	initOverlayElementEvent();
	initBodyMouseMoveEvent();
	// workspace
	$("#workspaceDialog").dialog({
		autoOpen : false
	});

	$("#workspaceDialog").dialog("option", "height", $("#workspaceDialogHeight").html());
	//$("#workspaceDialog").dialog("option", "height", $("#workspace").height() + 75);
	//$("#workspaceDialog").dialog("option", "height", $("#workspace").attr("height") * 1 + 75);
	$("#workspaceDialog").dialog("option", "modal", true);
	//$("#workspaceDialog").dialog("option", "width", $("#workspace").attr("width") * 1 + 50);
	//$("#workspaceDialog").dialog("option", "width", $("#workspace").width() + 50);
	$("#workspaceDialog").dialog("option", "width", $("#workspaceDialogWidth").html());
	$("#workspaceDialog").on("dialogclose", function(event, ui) {
		$('#toolboxDialog').dialog('close');
	});
	$("#openDialogBtn").click(function() {
		$("#explanationDialog").dialog({
			autoOpen : false
		});
		$("#explanationDialog").dialog("option", "modal", true);
		$("#explanationDialog").dialog("option", "title", 'Uitleg "afloop"');
		$("#explanationDialog").dialog("option", "width", 750);
		$("#explanationDialog").on( "dialogbeforeclose", function( event, ui ) {
			$("#workspaceDialog").dialog("open");
		} );
		$("#explanationDialog").dialog("open");
	});

	// imageUpload
	$("#imageUploadDialog").dialog({
		autoOpen : false
	});
	$("#uploadImageBtn").click(function() {
		$("#imageUploadDialog").dialog("open");
	});
	$("#imageUploadDialog").dialog("option", "modal", true);
	$('#imageUploadDialog').dialog("option", "width", $("#imageUploadDialogWidth").html());
	
	
	// toolbox
	$("#toolboxDialog").dialog({
		autoOpen : false
	});
	$("#toolboxDialog").dialog("option", "modal", true);
	$("#openToolboxBtn").click(function() {
		$("#toolboxDialog").dialog("open");
	});
	$("#workspace img").each(function() {
		$(this).resizable({
			handles : 'all',
			containment : $("#workspace"),
			aspectRatio : $("#keepProportions").is(':checked'),
			start : function(event, ui) {
				startEditingImage();
			},
			stop : function(event, ui) {
				stopEditingImage();
			}
		}).parent().draggable({
			containment : $("#workspace"),
			start : function(event, ui) {
				startEditingImage();
			},
			stop : function(event, ui) {
				stopEditingImage();
			}
		});
	});

	$('.overlayElement').on('mousedown', function(event) {
		var img = null;
		$('#workspace img').each(function() {
			if (isMouseIn($(this))) {
				img = $(this);
			}
		});
		if(img){
			$(img).trigger(event);
		}
	});

	function startEditingImage() {
		$('body').unbind('mousemove');
		$('.overlayElement').unbind('mousemove');
		$('.overlayElement').each(function() {
			$(this).removeClass('hidden');
		});
	}

	function stopEditingImage() {
		initOverlayElementEvent();
		initBodyMouseMoveEvent();
	}
	
	function initDeleteImage(){
		$(".deleteImage").click(function(e){
			$(this).parent().parent().find("input").val('');
			$(this).parent().parent().find("input").change(function(){
				initPreview($(this).parent().parent(), $(this).parent().parent().find("input"));
			});
			
			var id = $(this).parent().parent().find(".id").html();
			$(".previewImage" + id).html('<img src="/img/noImage.png" />');
			$("#workspace #image" + id).remove();
		});
	}

	function initOverlayElementEvent() {
		$('.overlayElement').on('mousemove', function(event) {
			var inImage = false;
			$('#workspace .ui-resizable-handle').each(function() {
				if (isMouseIn($(this))) {
					inImage = true;
				}
			});
			if (inImage) {
				$('.overlayElement:not(.hidden)').each(function() {
					$(this).addClass('hidden');
				});
			}
		});
	}

	function initBodyMouseMoveEvent() {
		// TODO make more performant
		$('body').on('mousemove', function(event) {
			var inImage = false;
			$('#workspace .ui-resizable-handle').each(function() {
				if (isMouseIn($(this))) {
					inImage = true;
				}
			});
			if (!inImage) {
				$('.overlayElement.hidden').each(function() {
					$(this).removeClass('hidden');
				});
			}
		});
	}

	function isMouseIn(element) {
		var gxstart = $(element).offset().left;
		var gxend = $(element).offset().left + $(element).width();
		var gystart = $(element).offset().top;
		var gyend = $(element).offset().top + $(element).height();

		var mouseX = event.pageX;// clientX;
		var mouseY = event.pageY;// clientY;
		var mouseIsInElement = false;
		if (gxstart < mouseX) {
			if (mouseX < gxend) {
				if (gystart < mouseY) {
					if (mouseY < gyend) {
						mouseIsInElement = true;
					}
				}
			}
		}

		return mouseIsInElement;
	}
}

function initNavUp(element){
	var row = $(element).parent().parent();
	var id = $(row).find(".id").html();
	var prevRow = $(row).prev();
	var prevRowId = $(prevRow).find(".id").html();
	$(row).find(".id").html(prevRowId);
	$(prevRow).find(".id").html(id);

	if (id == 5) {
		var tmpElement = $('<img class="nav nav-down" src="/img/arrow-down-icon.png" />');
		$(tmpElement).insertAfter(row.find(".nav-up"));
		$(prevRow).find(".nav-down").remove();
		$(tmpElement).click(function(e){
			initNavDown($(this));
		});
	}
	if (prevRowId == 1) {
		var tmpElement = $('<img class="nav nav-up" src="/img/arrow-up-icon.png" />');
		$(row).find(".nav-up").remove();
		$(tmpElement).insertBefore(prevRow.find(".nav-down"));
		$(tmpElement).click(function(e){
			initNavUp($(this));
		});
	}
	
	var img = $("#image" + id);
	var prevImg = $("#image" + prevRowId);
	$(img).parent().insertBefore($(prevImg).parent());
	$(img).attr("id", "image" + prevRowId);
	$(prevImg).attr("id", "image" + id);
	
	$(row).insertBefore(prevRow);
}

function initNavDown(element){
	var row = $(element).parent().parent();
	var id = $(row).find(".id").html();
	var nextRow = $(row).next();
	var nextRowId = $(nextRow).find(".id").html();
	$(row).find(".id").html(nextRowId);
	$(nextRow).find(".id").html(id);

	if (id == 1) {
		var tmpElement = $('<img class="nav nav-up" src="/img/arrow-up-icon.png" />');
		$(tmpElement).insertBefore(row.find(".nav-down"));
		$(nextRow).find(".nav-up").remove();
		$(tmpElement).click(function(e){
			initNavUp($(this));
		});
	}
	if (nextRowId == 5) {
		var tmpElement = $('<img class="nav nav-down" src="/img/arrow-down-icon.png" />');
		$(row).find(".nav-down").remove();
		$(tmpElement).insertAfter(nextRow.find(".nav-up"));
		$(tmpElement).click(function(e){
			initNavDown($(this));
		});
	}

	var img = $("#image" + id);
	var nextImg = $("#image" + nextRowId);
	$(img).parent().insertAfter($(nextImg).parent());
	$(img).attr("id", "image" + nextRowId);
	$(nextImg).attr("id", "image" + id);
	
	$(row).insertAfter($(row).next());
}

function resizeCanvasImage(img, canvas, maxWidth, maxHeight) {
	var imgWidth = img.width, imgHeight = img.height;

	var ratio = 1, ratio1 = 1, ratio2 = 1;
	ratio1 = maxWidth / imgWidth;
	ratio2 = maxHeight / imgHeight;

	// Use the smallest ratio that the image best fit into the maxWidth x
	// maxHeight box.
	if (ratio1 < ratio2) {
		ratio = ratio1;
	} else {
		ratio = ratio2;
	}

	var canvasContext = canvas.getContext("2d");
	var canvasCopy = document.createElement("canvas");
	var copyContext = canvasCopy.getContext("2d");
	var canvasCopy2 = document.createElement("canvas");
	var copyContext2 = canvasCopy2.getContext("2d");
	canvasCopy.width = imgWidth;
	canvasCopy.height = imgHeight;
	copyContext.drawImage(img, 0, 0);

	// init
	canvasCopy2.width = imgWidth;
	canvasCopy2.height = imgHeight;
	copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

	var rounds = 2;
	var roundRatio = ratio * rounds;
	for (var i = 1; i <= rounds; i++) {
		console.log("Step: " + i);

		// tmp
		canvasCopy.width = imgWidth * roundRatio / i;
		canvasCopy.height = imgHeight * roundRatio / i;

		copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);

		// copy back
		canvasCopy2.width = imgWidth * roundRatio / i;
		canvasCopy2.height = imgHeight * roundRatio / i;
		copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

	} // end for

	// copy back to canvas
	canvas.width = imgWidth * roundRatio / rounds;
	canvas.height = imgHeight * roundRatio / rounds;
	canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);
}
		
function initSlider(imageSliderId, imageSliderValueId, imageId){
	$( imageSliderId ).slider({
		//50 on slider == image size of 100%
		value: 50,
		min: 5,
		change: function( event, ui ) {
		
			var imageResizePercentage = getImageResizePercentage(ui);
			var imageResizePercentageString = imageResizePercentage + "%";
			
			var toolHolder = $(this).parent(); //container with the slider, label, ...
			var correspondingLabel = $(toolHolder).find(".label");
			$(correspondingLabel).html(imageResizePercentageString);
			
			$(imageId).css('width', ($(imageId).css('width').replace("px", "") * (imageResizePercentage/100)) + "px" );
			$(imageId).css('height', ($(imageId).css('height').replace("px", "") * (imageResizePercentage/100)) + "px" );
			$(imageId).parent().css('width', ($(imageId).parent().css('width').replace("px", "") * (imageResizePercentage/100)) + "px" );
			$(imageId).parent().css('height', ($(imageId).parent().css('height').replace("px", "") * (imageResizePercentage/100)) + "px" );
		},
		slide: function(event, ui) {
			var imageResizePercentageString = getImageResizePercentage(ui);
			$(imageSliderValueId + " .label").html(imageResizePercentageString + "%");
		}
	});

	initSliderLabel($(imageSliderValueId + " .sliderReset").parent().parent());
	
	$(imageSliderId).parent().parent().parent().parent().parent().removeClass("hidden");
	$(imageSliderValueId + " .sliderReset").click(function(e){
		var toolHolder = $(this).parent().parent(); //container with the slider, label, ...
		initSliderLabel(toolHolder);
	});
}

function initSliderLabel(toolHolder){
	var correspondingSlider = $(toolHolder).find(".slider");
	$(correspondingSlider).slider('value', 50);
	var correspondingLabel = $(toolHolder).find(".sliderLabel .label");
	$(correspondingLabel).html("100%");
}

function getImageResizePercentage(ui){
	var value = ui.value;
	var imageResizePercentage = value * 2; //as 50% on slider == 100% on image
	return imageResizePercentage;
}

function dump(obj) {
	var out = '';
	for ( var i in obj) {
		out += i + ": " + obj[i] + "\n";
	}

	document.write(out);

	// or, if you wanted to avoid alerts...

	var pre = document.createElement('pre');
	pre.innerHTML = out;
	document.body.appendChild(pre)
}